<?php
namespace App\Http\Controllers\ApiXcx;

use App\Http\lib\wxBizDataCrypt\WXBizDataCrypt;
use App\Service\ApiXcx\UserService;
use Illuminate\Http\Request;

class WxAuthController extends BaseController
{
    //微信授权

    protected $app_id = 'wx081bb28635ee4455';//'wxbf3d9e70e4eb9fb0';
    protected $app_secret = 'f0a1e29245c9186cddd4f155302a6707';//'65df5b844267bf0c8624758557b8ccc7';

    /**
     * 用户详细授权，access_token
     */
    public function wxtoken(Request $request)
    {
        //GET（请使用https协议） https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        $appid = $this->app_id; //env('WECHAT_APPID');
        $appsecret = $this->app_secret; //env('WECHAT_SECRET');
        $code = $request->get('code', '');
        $nickname = $request->get('nickname', '');
        $avatarUrl= $request->get('avatarUrl', '');
        $parent_id = $request->get('parent_id', 0);
        $card_id = $request->get('card_id', 0);
        file_put_contents('logs/wx'.date('Ymd',time()).'.log',
            toDate().'：零售端：'.json_encode($request->all(), JSON_UNESCAPED_UNICODE).PHP_EOL,
            FILE_APPEND);
        if (!$code) {
            return $this->toJson(-2, 'CODE必须的');
        }
//        $nickname = $nickname ? $nickname : time() . rand(10000, 99999);
        $nickname = $nickname ? $nickname : '微信昵称';
        if ($code == '0000') {
            $openid = $code;
        } else {
            $url = 'https://api.weixin.qq.com/sns/jscode2session';
            $url .= '?appid=' . $appid;
            $url .= '&secret=' . $appsecret;
            $url .= '&js_code=' . $code;
            $url .= '&grant_type=authorization_code';
            $resCurl = $this->wxCurl($url);
            if ($resCurl['code'] < 0) {
                return $this->toJson(-2, $resCurl['msg']);
            }
            $openid = $resCurl['data']['openid'];
        }
        $pas = [
            'parent_id' => $parent_id,
            'card_id' => $card_id,
            'openid' => $openid,
            'nickname' => $nickname,
            'avatarUrl' => $avatarUrl,
        ];
        $res = (new UserService())->wxByOpenid($pas);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        $resData = [
            'openid' => $openid,
            'token' => $res['data'],
        ];
        return $this->toJson(0, '', $resData);
    }

    //获取用户手机号
    public function wxPhone(Request $request)
    {
        $appid = $this->app_id; //env('WECHAT_APPID');
        $appsecret = $this->app_secret; //env('WECHAT_SECRET');
        $encryptedData = $request->encryptedData;  //包括敏感数据在内的完整用户信息的加密数据
        $jscode = $request->code;  //用户登录授权获取到的code
        $iv = $request->iv;  //用户登录授权获取到的iv
        //用code 获取sessionkey
        $access_token='https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$appsecret.'&js_code='.$jscode.'&grant_type=authorization_code';
        $result = $this->wxCurl($access_token);
        $jsonarr = json_decode($result, true);
        $sessionKey = $jsonarr['session_key'];
        //获取手机号解密
        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
        if ($errCode == 0) {
            $js_data = json_decode($data,true);
            return $this->toJson(0,'success',$js_data);
        }else{
            return $this->toJson(-2,'授权失败');
        }
    }

    /*
     * 手机号快速验证
     * */
    public function wxFastPhone(Request $request)
    {
        $appid = $this->app_id; //env('WECHAT_APPID');
        $appsecret = $this->app_secret; //env('WECHAT_SECRET');
        $code = $request->get('code', '');
        $url_get = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
        $token_res = $this->wxCurl($url_get);
        $token = $token_res['data']['access_token'];
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" . $token;
        $data = ['code' => $code];
        $info = $this->postJson($url, $data);
        $rescode = $info['data']['errcode'];
        if($rescode == '0'){
            $phoneNumber = $info['data']['phone_info']['phoneNumber'];
            return $this->toJson(0, '', ['phoneNumber' => $phoneNumber]);
        }else{
            return $this->toJson(-2, '获取失败');
        }
    }

    /**
     * 构建CURL请求，单线程
     * @param $url 请求地址
     * @param $string 参数拼接的字符串
     * @param $method 请求方式：put、post、get、delete
     * @return $json
     */
    public function wxCurl($url)
    {
        $curl = curl_init(); //初始化
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        $output = curl_exec($curl);
        curl_close($curl);
        if (!$output) {
            return array('code'=>-1, 'msg'=>'请求失败');
        }
        $items = json_decode($output,true);
        return array('code' => 0, 'msg' => 'success', 'data' => $items);
    }

    /**
     * 提交JSON数据
     * @param $url 提交地址
     * @param $postData 提交数据
     * @author 买买提
     * @return array
     */
    public static function postJson($url, $postData, $header = []) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen(json_encode($postData)))
        );
        if ($header) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        if (!curl_exec($ch)) {
            $data = false;
        } else {
            $data = curl_multi_getcontent($ch);
        }
        curl_close($ch);
        if(!$data){
            return array('code'=>-1, 'msg'=>'请求失败');
        }
        $items = json_decode($data,true);
        return array('code' => 0, 'msg' => 'success', 'data' => $items);
    }
}